/*
 * Copyright 2022 Institute of Software Chinese Academy of Sciences, ISRC
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
import router from '@system.router';
import featureAbility from '@ohos.ability.featureAbility';
import display from '@ohos.display';
import http from '@ohos.net.http';
import prompt from '@system.prompt';

export default {
    data: {
        findList: [],
        friendsList: [],
        groupList: [],
        eventReturn: null
    },
    onInit() {
        console.info('mailList====>onInit :')
        this.$app.$def.chatData = []
        this.getFriends(true)
        this.getGroups(true)
        this.findList = this.$app.$def.mailList
//        this.title = this.$t('strings.world');
        console.log('宽度:' + display.width + "高度：" + display.height);
        this.grantPermission()
        //绑定事件
        console.info('mailList====>eventBus start')
        let Bus = this.$app.$def.eventBus
        let refreshMailList = () => {
            console.info('[eventBus]mailList====>eventBus refreshMailList')
            this.getFriends(false)
            this.getGroups(false)
        }
        this.eventReturn = Bus.$on('refreshMailList', refreshMailList)
        console.info('mailList====>eventBus end')
    },
    onDestroy() {
        let Bus = this.$app.$def.eventBus;
        Bus.$off('refreshMailList',this.eventReturn)
    },
    onShow(){
        console.info('mailList====>onShow :')
    },
    getGroups(initSessionList = false) {
        /*测试通讯录好友跳转*/
        this.groupList = this.$app.$def.groupList
        /*获取通讯录好友信息*/
        console.info('mailList====>getgroupList:' + this.$app.$def.uid)
        let httpRequest= http.createHttp();
        let promise = httpRequest.request("http://" + this.$app.$def.ip +"/group/groupList/" + this.$app.$def.uid, {
            connectTimeout: 60000,
            readTimeout: 60000,
            header: {
                'Content-Type': 'application/json'
            }
        });
        promise.then((value) => {
            this.re  = JSON.parse(value.result.toString())
            let re = this.re;
            console.info('mailList====>get groupList re: '+JSON.stringify(re))
            if(re.code == 200) {
                this.$app.$def.groupList = []
                for (let i = 0; i < re.data.length; i++) {
                    let img = '/common/images/sessionPic/img_' + Math.round(Math.random()*7+1) + '.png'
                    let group = {
                        id: re.data[i].groupId,
                        imgUrl: img,
                        text: re.data[i].groupId,
                        url: '',
                        style: 'pengyou'
                    }
                    //session实时注入群聊
                    let newSession = {
                        'title': re.data[i].groupId,
                        'topMessage': '你们已经成为好友了',
                        'imgUrl': img,
                        'readTime': new Date().getHours() + ':' + new Date().getMinutes(),
                        'unRead': 'group',
                        'uid':[re.data[i].groupId],
                        'checkId':[],
                        'MsgList': [{isMe: false,
                                        sendUid:"",
                                        messageType: 0,
                                        content:'华为鸿蒙系统是一款全新的面向全场景的分布式操作系统，创造一个超级虚拟终端互联的世界',
                                        profPicUrl:'/common/images/bob.jpg',
                                        createTime:"",},
                                    {isMe: false,
                                        sendUid:"",
                                        messageType: 1,
                                        content:'/common/images/harmonyos.jpg',
                                        profPicUrl:'/common/images/bob.jpg',
                                        createTime:"",}]
                    }
                    this.$app.$def.groupList.push(group)
                    if(initSessionList) {
                        this.$app.$def.chatData.push(newSession);
                    }
                }
                this.groupList = this.$app.$def.groupList
            }
        }).catch((err) => {
            console.error(`groupList====> errCode:${err.code}, errMessage1:${err.data}`);
        });
    },
    getFriends(initSessionList = false) {
        /*测试通讯录好友跳转*/
        this.friendsList = this.$app.$def.friendsList
        /*获取通讯录好友信息*/
        console.info('mailList====>getFriends :' + this.$app.$def.uid)
        console.log('mailList====>getFriends :' + this.$app.$def.uid)
        let httpRequest= http.createHttp();
        let promise = httpRequest.request("http://" + this.$app.$def.ip +"/user/friendsList/" + this.$app.$def.uid, {
            connectTimeout: 60000,
            readTimeout: 60000,
            header: {
                'Content-Type': 'application/json'
            }
        });
        promise.then((value) => {
            this.re  = JSON.parse(value.result.toString())
            let re = this.re;
            console.info('mailList====>getFriends re: '+JSON.stringify(re))
            if(re.code == 200) {
                this.$app.$def.friendsList = [];
                for (let i = 0; i < re.data.length; i++) {
                    let img = '/common/images/sessionPic/img_' + Math.round(Math.random()*7+1) + '.png'
                    let friend = {
                        id: re.data[i].touid,
                        imgUrl: img,
                        text: re.data[i].touid,
                        url: '',
                        style: 'pengyou'
                    }
                    //session实时注入单聊
                    let newSession = {
                        'title': re.data[i].touid,
                        'topMessage': '你们已经成为好友了',
                        'imgUrl': img,
                        'readTime': new Date().getHours() + ':' + new Date().getMinutes(),
                        'unRead': 'say',
                        'uid':[re.data[i].touid],
                        'checkId':[],
                        'MsgList': [{isMe: false,
                                        sendUid:"",
                                        messageType: 0,
                                        content:'华为鸿蒙系统是一款全新的面向全场景的分布式操作系统，创造一个超级虚拟终端互联的世界',
                                        profPicUrl:'/common/images/bob.jpg',
                                        createTime:"",},
                                    {isMe: false,
                                        sendUid:"",
                                        messageType: 1,
                                        content:'/common/images/harmonyos.jpg',
                                        profPicUrl:'/common/images/bob.jpg',
                                        createTime:"",}]
                    }
                    this.$app.$def.friendsList.push(friend);
                    if(initSessionList) {
                        this.$app.$def.chatData.push(newSession);
                    }
                }
                this.friendsList = this.$app.$def.friendsList;
            }
        }).catch((err) => {
            console.error(`createGroup====> errCode:${err.code}, errMessage1:${err.data}`);
        });
    },
    /*获取部分权限*/
    grantPermission() {
        console.info('grantPermission')
        let context = featureAbility.getContext()
        context.requestPermissionsFromUser(['ohos.permission.DISTRIBUTED_DATASYNC'], 666, function (result) {
            console.info(`grantPermission,requestPermissionsFromUser`)
        })
    },
    agreeAdd() {
        if(this.$app.$def.agreeuid === ''){
            prompt.showToast({
                message: '没有新的好友请求',
                duration: 2000,
            })
        }else {
            router.push({
                uri: "pages/agreeFriends/agreeFriends"
            })
        }
    },
    itemClick(chat){
        router.push({
            uri: "pages/dialogPage/dialogPage",
            params: {
                'title': chat.title,
                'type': chat.topMessage,
                'imgUrl': chat.imgUrl,
                'reads': chat.readTime,
                'likes': chat.unRead,
            }
        });
    },
    switchToDetail(id, sayOrGroup){
        if(sayOrGroup==='say'){
            console.info('mailList====>switchToDetail: '+id)
            this.$app.$def.mailFriendId = id;
            router.push({
                uri: "pages/dialogPage/chatMessagePage/friendDetails/friendDetails",
                params: {
                    sayOrGroup: sayOrGroup,
                    sayOrGroup_ID: id,
                },
            });
        }
        else if(sayOrGroup==='group'){
            this.$app.$def.mailFriendId = id;
            router.push({
                uri: "pages/dialogPage/dialogPage",
                params: {
                    sayOrGroup: sayOrGroup
                },
            });
        }
    },


}



